<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="en">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta property="og:type" content="website">
<meta property="og:title" content="LinRaise&#39;s Blog">
<meta property="og:url" content="http://yoursite.com/page/2/index.html">
<meta property="og:site_name" content="LinRaise&#39;s Blog">
<meta property="og:locale" content="en_US">
<meta property="article:author" content="LinRaise">
<meta name="twitter:card" content="summary">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"right","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/page/2/"/>





  <title>LinRaise's Blog</title>
  








<meta name="generator" content="Hexo 4.2.1"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="en">

  
  
    
  

  <div class="container sidebar-position-right 
  page-home">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">LinRaise's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            About
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            Tags
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            Categories
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            Archives
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            Search
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="Searching..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            
  <section id="posts" class="posts-expand">
    
      

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2020/07/16/%E8%85%BE%E8%AE%AF%E4%B8%80%E9%81%93%E9%9D%A2%E8%AF%95%E9%A2%98/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="LinRaise">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="LinRaise's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
                
                <a class="post-title-link" href="/2020/07/16/%E8%85%BE%E8%AE%AF%E4%B8%80%E9%81%93%E9%9D%A2%E8%AF%95%E9%A2%98/" itemprop="url">腾讯一道面试题</a></h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2020-07-16T12:41:14+00:00">
                2020-07-16
              </time>
            

            
              <span class="post-meta-divider">|</span>
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-check-o"></i>
              </span>
              
                <span class="post-meta-item-text">Post modified&#58;</span>
              
              <time title="Post modified" itemprop="dateModified" datetime="2020-07-16T12:41:14+00:00">
                2020-07-16
              </time>
            
          </span>

          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <p>28）给定一数组a[N]，我们希望构造数组b [N]，其中b[j]=a[0]*a[1]…a[N-1] / a[j]，在构造过程中，不允许使用除法：<br>要求O（1）空间复杂度和O（n）的时间复杂度；<br>除遍历计数器与a[N] b[N]外，不可使用新的变量（包括栈临时变量、堆空间和全局静态变量等）；<br>实现程序（主流编程语言任选）实现并简单描述。<br>先忽略题目所给的任何限制，天马行空想象一下，能想象到什么解法？<br>１.最简单的办法，将a[0]到a[N-1]全乘起来，再遍历数组，依次除以a[j]即可，这是最简单的办法，但是，不允许使用除法，此法不可行．<br>２.既然不能使用除法，我们可以换一种思维方式：先将a[j]左边的数全乘一遍，a[j]右边的数全乘一遍，二者再乘起来，就可以避免除法，得到了a[j]的值．这样子，显然要求得每一个a[i]都需要遍历一遍数组,时间复杂度为o(n)，求完所有的a[0]到a[N-1],时间复杂度为o(n^2).不符合题意．但是，这个办法给我们提供了一种可能性，那就是，能不能在二层嵌套循环中整合成一层嵌套循环？这个问题暂时不得而知，但是，我们可以知道的是，我们可以实现这个o(n^2)的方法，先实现出来再看看接下来能不能降低时间复杂性．<br>o(n^2)时间复度性的代码：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">void ConstructArray(int* A,int* B,int N)</span><br><span class="line">&#123;</span><br><span class="line">	for(int i&#x3D;0;i&lt;N;++i)</span><br><span class="line">	&#123;</span><br><span class="line">		B[i]&#x3D;1;</span><br><span class="line">		for(int j&#x3D;0;j&lt;N;++j)</span><br><span class="line">		&#123;</span><br><span class="line">			if(j !&#x3D; i)</span><br><span class="line">			&#123;</span><br><span class="line">				B[i]&#x3D;B[i]*A[j];</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<p>即: | 为分割线．<br>表：1-1<br>A[0]=１｜<em>A[1]*A[2]</em>……..<em>A[N-1]<br>A[1]=A[0]<em>｜</em>A[2]<em>A[3]…….A[N-1]<br>A[2]=A[0]</em>A[1]<em>｜</em>A[3]</em>……A[N-1]<br>……<br>A[j]=A[0<em>A[1]</em>…A[j-1]｜A[j+1]<em>A[j+2]</em>…A[N-1]<br>上面的代码实现思路是这样子的：将问题分为两部分：对于A[0]，A[1]…..到A[N-1]的每一个A[i]，通过一遍的循环遍历数组得出结果．这样子就形<br>成二层嵌套．<br>现在，我们需要换一个角度想，能不能将分割线｜左右两边的结果全算出来保存在一个数组中，然后，两个数组对应相乘就可以解决问题了．中间，我们不需要两个暂时数组，可以利用B[N]数组的特点来完成这种累积的过程．</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">void ConstructArray(int* A,int* B,int N)</span><br><span class="line">&#123;</span><br><span class="line">	if(!A || !B) return ;</span><br><span class="line">	B[0]&#x3D;1;</span><br><span class="line">	for(int i&#x3D;0;i&lt;&#x3D;N-2;++i)</span><br><span class="line">	&#123;</span><br><span class="line">		B[i+1]&#x3D;B[i]*A[i];&#x2F;&#x2F;对比表:1-1容易知道,构造分割线左边部分</span><br><span class="line">	&#125;</span><br><span class="line">	&#x2F;&#x2F;上面已经建立了一个金字塔式的左分割线部分，现在自底向上重复上面的操作就能建立右分割线部分</span><br><span class="line">	for(int i&#x3D;N-1;i&gt;&#x3D;1;--i)</span><br><span class="line">	&#123;</span><br><span class="line">		B[i]&#x3D;B[i]*B[0];</span><br><span class="line">		B[0]&#x3D;B[0]*A[i];</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>总结：</p>
<pre><code>题目要求比较苛刻，思维方式是利用B[i]构造左边金字塔型的数组，再构造右边的金字塔型．中间的转换比较巧妙．</code></pre>
          
        
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </div>
  
  
  
  </article>


    
      

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2020/07/16/%E5%85%A8%E6%8E%92%E5%BA%8F-%E5%85%AB%E7%9A%87%E5%90%8E-%E4%B8%89%E8%A7%92%E5%85%AB%E7%9A%87%E5%90%8E/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="LinRaise">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="LinRaise's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
                
                <a class="post-title-link" href="/2020/07/16/%E5%85%A8%E6%8E%92%E5%BA%8F-%E5%85%AB%E7%9A%87%E5%90%8E-%E4%B8%89%E8%A7%92%E5%85%AB%E7%9A%87%E5%90%8E/" itemprop="url">全排序-八皇后-三角八皇后</a></h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2020-07-16T12:37:26+00:00">
                2020-07-16
              </time>
            

            
              <span class="post-meta-divider">|</span>
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-check-o"></i>
              </span>
              
                <span class="post-meta-item-text">Post modified&#58;</span>
              
              <time title="Post modified" itemprop="dateModified" datetime="2020-07-16T12:37:26+00:00">
                2020-07-16
              </time>
            
          </span>

          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <p>假设要求字符串/数组的全排序，例如：”123”的全排序，第1位有3种选择，第2位有2种选择，第3位1种选择，时间复杂度显然是3!.实际上容易知道，对于n个字符，全排序一共有n!种可能，是n!时间复杂度的．我们需要找一个算法求出所有的可能的排序，最好的办法是递归，如果选用循环，需要n层嵌套，不太现实．假设我们已经拥有一个函数 FullPermutation(A[n])能将数组A[n]全排序，于是，我们可以将A[n]分为A[1]和A[n-1]两个子问题，其中，A[1]可以有n种选择，选择办法是：将A[1]和A[i]交换,其中，i=1,2,3,4……．记得交换后，需要复原．A[n-1]的全排序可以通过调用FullPermutation()完成．<br>递推公式：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">F(n):  &#x3D; Done n&#x3D;1  </span><br><span class="line">  &#x3D; n*F(n-1) n&gt;1</span><br></pre></td></tr></table></figure>

<p>由上面的分析和递推公式就很容易写出代码了：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> <span class="built_in">std</span>;</span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">Full_permutation</span><span class="params">(<span class="keyword">int</span>* A,<span class="keyword">int</span> beg,<span class="keyword">int</span> <span class="built_in">end</span>)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="keyword">if</span>(beg == <span class="built_in">end</span>)</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">0</span>;i&lt;=<span class="built_in">end</span>;++i)</span><br><span class="line">			<span class="built_in">cout</span>&lt;&lt;A[i]&lt;&lt;<span class="string">' '</span>;</span><br><span class="line">		<span class="built_in">cout</span>&lt;&lt;<span class="built_in">endl</span>;</span><br><span class="line">		<span class="keyword">return</span> ;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">for</span>(<span class="keyword">int</span> i=beg;i &lt;= <span class="built_in">end</span>; ++i)<span class="comment">//A[1]有n种选择，需要n次循环</span></span><br><span class="line">	&#123;</span><br><span class="line">		swap(A[beg],A[i]);　<span class="comment">//选择beg的值</span></span><br><span class="line">		Full_permutation(A,beg+<span class="number">1</span>,<span class="built_in">end</span>);<span class="comment">//求解n-1子问题</span></span><br><span class="line">		swap(A[beg],A[i]);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="keyword">int</span> A[<span class="number">8</span>]=&#123;<span class="number">0</span>,<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>,<span class="number">6</span>,<span class="number">7</span>&#125;;</span><br><span class="line">	Full_permutation(A,<span class="number">0</span>,<span class="number">7</span>);</span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>




<p>扩展：由时间复杂度为(n!)，我们容易联想到n皇后问题，最经典的八皇后问题：在8×8的国际象棋上摆放八个皇后，使其不能相互攻击，即任意两个皇后不得处在同一行、同一列或者同一对角斜线上。我们可以这么分析，先从行入手，第1个皇后可以在第1行上选择8个位置，第2个皇后可以在第2行选择7个位置(只要不和第1个皇后同列)，第3个皇后可以在第1行上选择6个位置(只要不和第1,2个皇后同列)．如果不考虑对角线的攻击方向，那么n皇后问题可以有n!个解，和上面的全排列一样．同样，我们可以先考虑行和列的n!种所有情况，然后排除对角线冲突的情况，进而缩小范围，就可以找出8皇后的解．基于这个想法，八皇后问题并不难．现在，我们还剩下最后一个问题？用什么数据结构保存皇后的二维坐标，其实很容易，用(i,A[i])就可以保存皇后的位置，即一个数组，索引i表示行，A[i]表示列．定义一个A[8]就可以表示八皇后．</p>
<p>由这个思路，代码：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> <span class="built_in">std</span>;</span><br><span class="line"><span class="function"><span class="keyword">bool</span> <span class="title">isLegalQueens</span><span class="params">(<span class="keyword">int</span>* A,<span class="keyword">int</span> <span class="built_in">end</span>)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">0</span>; i&lt;=<span class="built_in">end</span>; ++i)</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="keyword">for</span>(<span class="keyword">int</span> j=i+<span class="number">1</span>; j &lt;=<span class="built_in">end</span>; ++j)</span><br><span class="line">		&#123;</span><br><span class="line">			<span class="keyword">if</span>( A[j]-A[i] == j-i || A[j]-A[i] == i-j )<span class="comment">//两点的斜率如果为1或-1，则为不合法</span></span><br><span class="line">				<span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">Full_permutation</span><span class="params">(<span class="keyword">int</span>* A,<span class="keyword">int</span> beg,<span class="keyword">int</span> <span class="built_in">end</span>)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="keyword">if</span>(beg == <span class="built_in">end</span>)</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="keyword">if</span>(isLegalQueens(A,<span class="built_in">end</span>))</span><br><span class="line">		&#123;</span><br><span class="line">			<span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">0</span>;i&lt;=<span class="built_in">end</span>;++i)</span><br><span class="line">				<span class="built_in">cout</span>&lt;&lt;A[i]&lt;&lt;<span class="string">' '</span>;</span><br><span class="line">			<span class="built_in">cout</span>&lt;&lt;<span class="built_in">endl</span>;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">return</span> ;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">for</span>(<span class="keyword">int</span> i=beg;i &lt;= <span class="built_in">end</span>; ++i)<span class="comment">//A[1]有n种选择，需要n次循环</span></span><br><span class="line">	&#123;</span><br><span class="line">		swap(A[beg],A[i]);<span class="comment">//选择beg的值</span></span><br><span class="line">		Full_permutation(A,beg+<span class="number">1</span>,<span class="built_in">end</span>);<span class="comment">//求解n-1子问题</span></span><br><span class="line">		swap(A[beg],A[i]);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="keyword">int</span> A[<span class="number">8</span>]=&#123;<span class="number">0</span>,<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>,<span class="number">6</span>,<span class="number">7</span>&#125;;</span><br><span class="line">	Full_permutation(A,<span class="number">0</span>,<span class="number">7</span>);</span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>实训：<a href="http://acm.hdu.edu.cn/showproblem.php?pid=2804" target="_blank" rel="noopener">http://acm.hdu.edu.cn/showproblem.php?pid=2804</a></p>
<p>Queens<br>Problem Description</p>
<p>Everyone knows about the “eight queens problem”, but today you will solve a different one.<br>We are given triangle lattice of side n, as shown in the Figure below. A queen on the lattice can move along a straight line parallel to any of the sides of the triangle. How many queens can be placed on the lattice at most, without any two queens attacking each other?</p>
<p>一看到这道题，自然反应就是这道题：<a href="http://acm.hdu.edu.cn/showproblem.php?pid=1030，这一道题的思路是三维坐标绝对值之和．但是，上面的这一道题是经典的算法实现简单，但是原理却是博大精深的．" target="_blank" rel="noopener">http://acm.hdu.edu.cn/showproblem.php?pid=1030，这一道题的思路是三维坐标绝对值之和．但是，上面的这一道题是经典的算法实现简单，但是原理却是博大精深的．</a></p>
<p>有这么一个结论：</p>
<p>4、一边有 n 个圈的正三角形棋盘，</p>
<p>(1)当 n＝3k+1 时，最多可放置(2k+1)个皇后，k＝0，1，2，3，……</p>
<p>(2)当 n＝3k+2 时，最多可放置(2k+1)个皇后，k＝0，1，2，3，……</p>
<p>(3)当 n＝3k+3 时，最多可放置(2k+2)个皇后，k＝0，1，2，3，……</p>
<p>具体的证明过程见这篇论文：三角形八皇后问题证明</p>
<p>知道上面的结论之后，代码如下：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> <span class="built_in">std</span>;</span><br><span class="line"><span class="keyword">typedef</span> <span class="keyword">long</span> <span class="keyword">long</span> LLong;</span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	LLong n;</span><br><span class="line">	<span class="keyword">while</span>(<span class="built_in">cin</span>&gt;&gt;n &amp;&amp; n!=<span class="number">0</span>)</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="keyword">if</span>( n%<span class="number">3</span>== <span class="number">0</span>)</span><br><span class="line">			<span class="built_in">cout</span>&lt;&lt;<span class="number">2</span>*(n/<span class="number">3</span>)&lt;&lt;<span class="built_in">endl</span>;</span><br><span class="line">		<span class="keyword">else</span></span><br><span class="line">			<span class="built_in">cout</span>&lt;&lt;<span class="number">2</span>*(n/<span class="number">3</span>)+<span class="number">1</span>&lt;&lt;<span class="built_in">endl</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


          
        
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </div>
  
  
  
  </article>


    
      

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2020/07/16/%E7%BC%96%E7%A8%8B%E9%A2%98-%E7%94%A8%E9%80%92%E5%BD%92%E6%B1%82%E6%95%B0%E7%BB%84%E6%9C%80%E5%A4%A7%E5%80%BC%E7%9A%84%E4%BD%8D%E7%BD%AE/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="LinRaise">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="LinRaise's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
                
                <a class="post-title-link" href="/2020/07/16/%E7%BC%96%E7%A8%8B%E9%A2%98-%E7%94%A8%E9%80%92%E5%BD%92%E6%B1%82%E6%95%B0%E7%BB%84%E6%9C%80%E5%A4%A7%E5%80%BC%E7%9A%84%E4%BD%8D%E7%BD%AE/" itemprop="url">[编程题]用递归求数组最大值的位置</a></h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2020-07-16T12:34:18+00:00">
                2020-07-16
              </time>
            

            
              <span class="post-meta-divider">|</span>
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-check-o"></i>
              </span>
              
                <span class="post-meta-item-text">Post modified&#58;</span>
              
              <time title="Post modified" itemprop="dateModified" datetime="2020-07-16T12:34:18+00:00">
                2020-07-16
              </time>
            
          </span>

          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <p>题目:这道题难度并不大,因为是需要用递归的思想来解决,我们很容易就能够想到分治的思想.首先,定义一个函数MaxIndex()并假定它可以返回数组最值的索引(索引相对于数组开始而言,即相对开始偏移了多少.).至少MaxIndex()是如何工作的,暂时不需要管.只需要知道,它可以返回最大值的索引不妨设为p.因此可以将数组分为1和n-1两等份.对后者调用MaxIndex()可得到最大值下标偏移量.即最大值为A[p+1],相对于开始0需要多加1.用它和开始元素A[0]对比,如果大于,则返回p+1,否则返回0即可.</p>
<p>代码:</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//[编程题] 用递归求数组最大值的位置(下标,索引)</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> <span class="built_in">std</span>;</span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">MaxIndex</span><span class="params">(<span class="keyword">int</span>* A,<span class="keyword">int</span> n)</span><span class="comment">//时间复杂度为o(n)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="keyword">if</span>(n==<span class="number">1</span>)</span><br><span class="line">		<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">	<span class="keyword">int</span> p=MaxIndex(A+<span class="number">1</span>,n<span class="number">-1</span>);</span><br><span class="line">	<span class="keyword">return</span> A[<span class="number">0</span>]&gt;A[p+<span class="number">1</span>]? <span class="number">0</span>:p+<span class="number">1</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="keyword">int</span> A[]=&#123;<span class="number">7</span>,<span class="number">4</span>,<span class="number">2</span>,<span class="number">8</span>,<span class="number">0</span>,<span class="number">5</span>&#125;;</span><br><span class="line">	<span class="keyword">int</span> len=<span class="keyword">sizeof</span>(A)/<span class="keyword">sizeof</span>(A[<span class="number">0</span>]);</span><br><span class="line">	<span class="keyword">int</span> Index=MaxIndex(A,len);</span><br><span class="line">	<span class="built_in">cout</span>&lt;&lt;Index&lt;&lt;<span class="built_in">endl</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>分析,假设n个元素的MaxIndex()时间复杂度为T(n).则有T(n)=T(n-1)+θ(1).由等差数列递推式可知T(n)=θ(n).这和蛮力扫描法在时间上相同，而且还需要维护递归栈．显然不合算，能不能找到更好的时间复杂度算法，使时间复杂度降到lgn呢？只需要在划分的时候，平均一分为二．不就可以了吗？</p>
<p>代码：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">MaxIndex2</span><span class="params">(<span class="keyword">int</span>* A,<span class="keyword">int</span> n)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="keyword">if</span>(n==<span class="number">1</span>)</span><br><span class="line">		<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">	<span class="keyword">int</span> mid=n/<span class="number">2</span>;</span><br><span class="line">	<span class="keyword">int</span> left=MaxIndex(A,mid);</span><br><span class="line">	<span class="keyword">int</span> right=MaxIndex(A+mid,n-mid);</span><br><span class="line">	<span class="keyword">return</span> A[left] &gt; A[right+mid]?left : right+mid;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


          
        
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </div>
  
  
  
  </article>


    
      

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2020/07/16/%E7%AE%97%E6%B3%95%E5%AF%BC%E8%AE%BA%E7%AC%AC%E4%B8%89%E7%89%887-3%E8%AF%81%E6%98%8E/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="LinRaise">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="LinRaise's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
                
                <a class="post-title-link" href="/2020/07/16/%E7%AE%97%E6%B3%95%E5%AF%BC%E8%AE%BA%E7%AC%AC%E4%B8%89%E7%89%887-3%E8%AF%81%E6%98%8E/" itemprop="url">算法导论第三版7-3证明</a></h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2020-07-16T12:29:01+00:00">
                2020-07-16
              </time>
            

            
              <span class="post-meta-divider">|</span>
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-check-o"></i>
              </span>
              
                <span class="post-meta-item-text">Post modified&#58;</span>
              
              <time title="Post modified" itemprop="dateModified" datetime="2020-07-16T12:29:01+00:00">
                2020-07-16
              </time>
            
          </span>

          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <h1 id="1-积分法证明："><a href="#1-积分法证明：" class="headerlink" title="1.积分法证明："></a>1.积分法证明：</h1><p><img src="/2020/07/16/%E7%AE%97%E6%B3%95%E5%AF%BC%E8%AE%BA%E7%AC%AC%E4%B8%89%E7%89%887-3%E8%AF%81%E6%98%8E/20130511194903297" alt="img"></p>
<p>用mathtype另行敲了一遍，看起来可能会舒服一些。</p>
<p><img src="/2020/07/16/%E7%AE%97%E6%B3%95%E5%AF%BC%E8%AE%BA%E7%AC%AC%E4%B8%89%E7%89%887-3%E8%AF%81%E6%98%8E/20130512022359734" alt="img"></p>
<h1 id="2-拆分法证明："><a href="#2-拆分法证明：" class="headerlink" title="2.拆分法证明："></a>2.拆分法证明：</h1><p><img src="/2020/07/16/%E7%AE%97%E6%B3%95%E5%AF%BC%E8%AE%BA%E7%AC%AC%E4%B8%89%E7%89%887-3%E8%AF%81%E6%98%8E/20130512011113398" alt="img"></p>
<p>取这个有一点小技巧，这可以保证前边部分元素a比后边部分的元素个数b少，即a&lt;n/2 ,所以lgn-1比lgk要大，因为lgn-1－lgk＝lg(n/k)-1&gt;0。</p>

          
        
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </div>
  
  
  
  </article>


    
      

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2020/07/16/%E7%AE%97%E6%B3%95%E5%AF%BC%E8%AE%BA7-4-5/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="LinRaise">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="LinRaise's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
                
                <a class="post-title-link" href="/2020/07/16/%E7%AE%97%E6%B3%95%E5%AF%BC%E8%AE%BA7-4-5/" itemprop="url">算法导论7.4-5</a></h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2020-07-16T12:27:00+00:00">
                2020-07-16
              </time>
            

            
              <span class="post-meta-divider">|</span>
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-check-o"></i>
              </span>
              
                <span class="post-meta-item-text">Post modified&#58;</span>
              
              <time title="Post modified" itemprop="dateModified" datetime="2020-07-16T12:27:00+00:00">
                2020-07-16
              </time>
            
          </span>

          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <p>题目：</p>
<p>当输入数据已经“几乎有序时”，插入排序很快，在实际应用中，我们可以利用这一特点来提高快速排序的速度。当对一个长度小于k的子数组调用快速排序时，让它不做任何排序就返回。当上一层的快速排序调用返回后，对整个数组运行插入排序完成排序过程。证明：这一排序算法的期望时间复杂度为O(nk+nlg(n/k)).</p>
<p>解决方案：</p>
<p> quicksort在递归到只有几个元素大小的数组时开始用插入排序的方法。改进的快速排序方法在</p>
<p>期望时间=原始快排的期望时间+插入排序方法的期望时间。</p>
<p>这里还是要用到7.4（算法导论第7章）的分析方法。对于快排还要计算期望比较次数。</p>
<p>因为被划分在同一个小数组k中的元素，是不会在快排里比较的。所以Xij只要计算那些i和j相差k-1个以上的元素比较就可以了。</p>
<p>定义一个元素集合Zij={zi,zi+1,,,,,,,,zj}</p>
<p>定义一个指示器随机变量Xij=I{zi与zj进行了比较}</p>
<p>E[Xij]=Pr[Xij]=Pr{zi与zj进行了比较}=Pr{zi是Zij的主元}+Pr{zj是Zij的主元}=2/(j-i+1)//因为在快排中，二者能够比较，则其中一个必是主元</p>
<p>快速排序的期望比较次数E[Xij]为</p>
<p><img src="/2020/07/16/%E7%AE%97%E6%B3%95%E5%AF%BC%E8%AE%BA7-4-5/20130511234131617" alt="img"></p>
<p>那么快排的期望时间是O(nlg(n/k))，假设优化后的快排产生的小数组大小O(k)，在每个大小O(k)的小数组里使用插入排序，时间复杂度为O(k^2),总共有O(n/k)个小数组，则插入排序时间为O(nk)，。那么把这些时间加起来就是O(nk+nlog(n/k))。</p>

          
        
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </div>
  
  
  
  </article>


    
      

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2020/07/16/%E7%AE%97%E6%B3%95%E5%AF%BC%E8%AE%BA7-5-%E4%B8%89%E6%95%B0%E5%8F%96%E4%B8%AD%E5%88%92%E5%88%86/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="LinRaise">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="LinRaise's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
                
                <a class="post-title-link" href="/2020/07/16/%E7%AE%97%E6%B3%95%E5%AF%BC%E8%AE%BA7-5-%E4%B8%89%E6%95%B0%E5%8F%96%E4%B8%AD%E5%88%92%E5%88%86/" itemprop="url">算法导论7-5(三数取中划分)</a></h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2020-07-16T11:35:19+00:00">
                2020-07-16
              </time>
            

            
              <span class="post-meta-divider">|</span>
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-check-o"></i>
              </span>
              
                <span class="post-meta-item-text">Post modified&#58;</span>
              
              <time title="Post modified" itemprop="dateModified" datetime="2020-07-16T11:35:19+00:00">
                2020-07-16
              </time>
            
          </span>

          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <p>算法导论7－5：</p>
<p>a.</p>
<p>对于i=2,3,4,………..,n-1,请给出以n和i表示的Pi的准确表示式：</p>
<p>从n个数中选择3个，一共有<img src="https://img-blog.csdn.net/20130512182518216" alt>种情况，要求i是3个数中的中位数，则当i选定时，剩余的2个数中，必须其中一个在i左边，一个在i右边，i左边有i-1种选择，i右边有n-i种选择，</p>
<p>则<img src="/2020/07/16/%E7%AE%97%E6%B3%95%E5%AF%BC%E8%AE%BA7-5-%E4%B8%89%E6%95%B0%E5%8F%96%E4%B8%AD%E5%88%92%E5%88%86/20130512183001953" alt></p>
<p>(<em>i</em>−1)(<em>n</em>−<em>i</em>)<em>C</em>3</p>
<p>b.(<em>i</em>−1)(<em>n</em>−<em>i</em>)<em>C</em>3_n_<br>由a.公式可知道选取中位数的概率等于<img src="/2020/07/16/%E7%AE%97%E6%B3%95%E5%AF%BC%E8%AE%BA7-5-%E4%B8%89%E6%95%B0%E5%8F%96%E4%B8%AD%E5%88%92%E5%88%86/20130512183001953" alt>)，平凡实现Pi=1/n,(<em>i</em>−1)(<em>n</em>−<em>i</em>)<em>C</em>3_n_<br>两个相比取极限为</p>
<p><img src="/2020/07/16/%E7%AE%97%E6%B3%95%E5%AF%BC%E8%AE%BA7-5-%E4%B8%89%E6%95%B0%E5%8F%96%E4%B8%AD%E5%88%92%E5%88%86/20130512190135096" alt>，所以增加了50%</p>
<p>(<em>i</em>−1)(<em>n</em>−<em>i</em>)<em>C</em>3_n_(<em>i</em>−1)(<em>n</em>−<em>i</em>)<em>C</em>3</p>
<p><img src="/2020/07/16/%E7%AE%97%E6%B3%95%E5%AF%BC%E8%AE%BA7-5-%E4%B8%89%E6%95%B0%E5%8F%96%E4%B8%AD%E5%88%92%E5%88%86/20130512194926270" alt></p>
<p>(<em>i</em>−1)(<em>n</em>−<em>i</em>)<em>C</em>3_n_</p>

          
        
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </div>
  
  
  
  </article>


    
  </section>

  
  <nav class="pagination">
    <a class="extend prev" rel="prev" href="/"><</a><a class="page-number" href="/">1</a><span class="page-number current">2</span>
  </nav>


          </div>
          


          

        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">LinRaise</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">16</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">2</span>
                  <span class="site-state-item-name">categories</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">1</span>
                  <span class="site-state-item-name">tags</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">LinRaise</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  

  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
